from applications.extensions import ma
from marshmallow import fields, validate
from applications.models import Category,Article


class ArticleSchema(ma.Schema):
    articleId = fields.Integer(attribute="id")
    categoryId = fields.Str(attribute="category_id")
    title = fields.Str()
    author = fields.Str()
    linkurl = fields.Str()
    hitnum = fields.Integer()
    sharenum = fields.Integer()
    ip = fields.Str()
    releaseuser = fields.Integer()
    coverimg = fields.Str()
    lunbo = fields.Integer()
    lunboimg = fields.Str()
    status = fields.Str(validate=validate.OneOf(["0", "1"]))
    sort = fields.Integer()
    allsort = fields.Integer()
    literemark = fields.Str()
    remark = fields.Str()
    releaseTime = fields.Str(attribute="release_time")
    createTime = fields.Str(attribute="create_time")
    updateTime = fields.Str(attribute="update_time")
    categoryname=fields.Method("getcname")

    def getcname(self, obj):
        if obj.category_id != None:
            return Category.query.filter_by(id=obj.category_id).first().category_name
        else:
            return None
